import  pymysql
class DB:
    def __init__(self,database,host ='localhost',user ='root',password ='root',
                 charset='utf8',cursor_type=pymysql.cursors.Cursor):
        self.__conn = pymysql.connect(host=host, user=user, password=password, charset=charset,
                                      database=database)
        self.cursor =self.__conn.cursor(cursor_type)
    def read(self,sql,params_list=[]):
        try:
            rows=self.__cursor.execute(sql, params_list)
            data = self.__cursor.fetchall()
        except Exception as e:
            print('sql语句有问题')
            return None,'No Data'
        return rows,data

    def Write(self,sql):
        try:
            rows = self.__cursor.execute(sql)
        except Exception as e:
            self.__conn.rollback()
            return 0
        else:
            self.__conn.commit()
        return rows

    def __def__(self):
        self.cursor.close()
        self.conn.close()


if __name__ == '__main__':
    # db = DB('advanced',cursor_type =pymysql.cursors.DictCursor)
    # rows,data=db.read('select * from student')
    # print(data)
    # name = input ('name:')
    # rows,data =db.read(f'select * from stydent where stu_name = %s',[name])
    # print(data)

    db = DB('advanced',cursor_type =pymysql.cursors.DictCursor)
    rows,data = db.read('select * from student')
    if rows:
        print(rows,data)
    rows =db.write("INSERT INTO student(stu_no, stu_name) VALUES('itsrc-015', '周杰伦1')")
    if rows:
        print('写入成功')
